package ru.hh.team02.chat.database;

import ru.hh.team02.chat.messaging.Message;
import ru.hh.team02.chat.messaging.PrivateMessage;
import ru.hh.team02.chat.server.Services;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections.*;

public class DatabaseServiceDerby implements DatabaseServiceInterface {
    private String dbURL = "jdbc:derby:hh0001team02;user=team02;create=false";
    private Connection conn = null;
    private Statement stmt = null;
    private PreparedStatement clientExisisStatement;
    private PreparedStatement getPasswordByClientNameStatement;
    private PreparedStatement getRoomNameByClientNameStatement;
    private PreparedStatement putNewPersonalMessageIntoDatabaseStatement1;
    private PreparedStatement putNewPersonalMessageIntoDatabaseStatement2;
    private PreparedStatement markPersonalMessageAsDeliveredStatement;
    private PreparedStatement getAllUndeliveredMessagesToTheClientStatement;
	private PreparedStatement getMessagesByIdStatement;
	private PreparedStatement getAllRoomsStatement;
	private PreparedStatement changeRoomStatement1;
	private PreparedStatement changeRoomStatement2;
	
	
    public DatabaseServiceDerby() {
        try {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
            //Get a connection
            conn = DriverManager.getConnection(dbURL);
			clientExisisStatement = conn.prepareStatement("select id from users where name = ?");
			getPasswordByClientNameStatement = conn.prepareStatement("select password from users where name = ?");
			getRoomNameByClientNameStatement = conn.prepareStatement("select rooms.name from users join rooms on users.room_id = rooms.id where users.name = ?");
			putNewPersonalMessageIntoDatabaseStatement1 = conn.prepareStatement("select id from users where name = ?");
			putNewPersonalMessageIntoDatabaseStatement2 = conn.prepareStatement("insert into messages(message, rctpto_id) values (?, ?)", Statement.RETURN_GENERATED_KEYS);
			markPersonalMessageAsDeliveredStatement = conn.prepareStatement("delete from messages where id = ?");
			getAllUndeliveredMessagesToTheClientStatement = conn.prepareStatement("select messages.id, messages.message from messages " +
                                                    "join users on messages.rctpto_id = users.id " +
                                                    "where users.name = ?")
			getMessagesByIdStatement = conn.prepareStatement("select messages.message, users.name from messages " +
                                                    "join users on messages.rctpto_id = users.id " +
                                                    "where messages.id = ?");
			getAllRoomsStatement = conn.prepareStatement("select name from rooms");
			changeRoomStatement1 = conn.prepareStatement("select id from rooms where rooms.name = ?")
			changeRoomStatement2 = conn.prepareStatement("update users set room_id = ? where name = ?")
        } catch (Exception except) {
            except.printStackTrace();
        }
    }

    public void Close() {
        try  {
			clientExisisStatement.close();
			getPasswordByClientNameStatement.close();
			getRoomNameByClientNameStatement.close();
			putNewPersonalMessageIntoDatabaseStatement1.close();
			putNewPersonalMessageIntoDatabaseStatement2.close();
			markPersonalMessageAsDeliveredStatement.close();
			getAllUndeliveredMessagesToTheClientStatement.close();
			getMessagesByIdStatement.close();
			getAllRoomsStatement.close();
			changeRoomStatement1.close();
			changeRoomStatement2.close();
			
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                DriverManager.getConnection("jdbc:derby:;shutdown=true");
                conn.close();
            }
        }
        catch (SQLException sqlExcept)  {
            if ( !sqlExcept.getSQLState().equals("XJ015") ) {
                sqlExcept.printStackTrace();
            }
        }
    }

    @Override
    public boolean clientExists(String name) {
        boolean result = false;
        try {
			clientExistsStatement.setString(1, name);
            ResultSet resultSet = clientExistsStatement.executeQuery();
            result = (resultSet.next());
            resultSet.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
        }
        return result;
    }

    @Override
    public String getPasswordByClientName(String name) {
        String result = null;
        try {
			getPasswordByClientNameStatement.setString(1, name);
            ResultSet resultSet = getPasswordByClientNameStatement.executeQuery();
            if (resultSet.next()) {
                result = resultSet.getString("password");
            }
            resultSet.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
        }
        return result;
    }

    @Override
    public String getRoomNameByClientName(String name) {
        String result = null;
        try {
			getRoomNameByClientNameStatement.setString(1, name);
            ResultSet resultSet = getRoomNameByClientNameStatement.executeQuery();
            if (resultSet.next()) {
                result = resultSet.getString("name");
            }
            resultSet.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
        }
        return result;
    }

    @Override
    public int putNewPersonalMessageIntoDatabase(String message, String recepientName) {
        int result = 0;
        try {
			putNewPersonalMessageIntoDatabaseStatement1.setString(1, recepientName);			
            ResultSet resultSet = putNewPersonalMessageIntoDatabaseStatement1.executeQuery();
            if (resultSet.next()) {
                int rctpto_id = resultSet.getInt("id");
				putNewPersonalMessageIntoDatabaseStatement2.setString(1, message);			
				putNewPersonalMessageIntoDatabaseStatement2.setInt(2, rctpto_id);			
                putNewPersonalMessageIntoDatabaseStatement2.executeUpdate();
                ResultSet generatedKeys = putNewPersonalMessageIntoDatabaseStatement2.getGeneratedKeys();
                if (generatedKeys.next()) {
                    result = generatedKeys.getInt(1);
                }
                generatedKeys.close();
            }
            resultSet.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
        }

        Services.ADMIN_LOGGER.write(message + " in database");
        return result;
    }

    @Override
    public boolean markPersonalMessageAsDelivered(int id) {
        String message = getMessagesById(id).getText();

        try {
			markPersonalMessageAsDeliveredStatement.setInt(1, id);
            markPersonalMessageAsDeliveredStatement.executeUpdate();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
            return false;
        }

        Services.ADMIN_LOGGER.write(message + " has been delivered and deleted from DB.");
        return true;
    }

    @Override
    public List<Message> getAllUndeliveredMessagesToTheClient(String clientName) {
        List<Message> result = new ArrayList<>();
        try {
			getAllUndeliveredMessagesToTheClientStatement.setString(1, clentName);
            ResultSet resultSet = getAllUndeliveredMessagesToTheClientStatement.executeQuery();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String message  = resultSet.getString("message");
                result.add(new PrivateMessage(message, id));
            }
            resultSet.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
            return null;
        }

        for (Message m : result) {
            String message = m.getText();
            Services.ADMIN_LOGGER.write(message + " is on the way");
        }

        return result;
    }

    @Override
    public PrivateMessage getMessagesById(int id) {
        PrivateMessage result = null;
        try {
			getMessagesByIdStatement.setInt(1, id);
            ResultSet resultSet = getMessagesByIdStatement.executeQuery();
            if (resultSet.next()) {
                String message  = resultSet.getString("message");
                String name  = resultSet.getString("name");
                result = new PrivateMessage(message, id);
            }
            resultSet.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
        }
        return result;
    }

    @Override
    public String[] getAllRooms() {
        List<String> result = new ArrayList<String>();
        try {
            ResultSet resultSet = getAllRoomsStatement.executeQuery();
            while (resultSet.next()) {
                result.add(resultSet.getString("name"));
            }
            resultSet.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
            return null;
        }


        return result.toArray(new String[result.size()]);
    }

    @Override
    public void changeRoom(String clientName, String room) {
        try {
			changeRoomStatement1.setString(1, room);
            ResultSet resultSet = changeRoomStatement1.executeQuery();
            if (resultSet.next()) {
                int room_id = resultSet.getInt("id");
				changeRoomStatement2.setInt(1, room_id);
				changeRoomStatement2.setString(2, clientName);
                changeRoomStatement2.executeUpdate();
            }
            resultSet.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
        }
    }
}
